import datetime, time

while True:
#    print("Checking ...")

    # todo past deadline
    records = db((db.todos.completion_date < datetime.datetime.now()) &
              (db.todos.email_sent == 'False') &
              (db.todos.status != 'Completed')).select()

    for record in records:
        if record.assignee.email == record.created_by.email:
            email = record.created_by.email
        else:
            email = ",".join([record.assignee.email, record.created_by.email])

        if mail.send(to = email, subject = record.title,
                 message = "The deadline for '%s' has passed." % record.title):
            record.update_record(email_sent = True)
#            print("Email to %s sent." % email)
#        else:
#            print("Email to %s failed." % email)

    # todo completed before deadline
    records = db((db.todos.completion_date > datetime.datetime.now()) &
              (db.todos.email_sent == 'False') &
              (db.todos.status == 'Completed')).select()

    for record in records:
        email = record.created_by.email
        if mail.send(to = email, subject = record.title,
                     message = "The '%s' has been completed."):
            record.update_record(email_sent = True)
#            print("Email to %s sent." % email)
#        else:
#            print("Email to %s failed." % email)

    db.commit()

    time.sleep(60) # check every minute
